package com.jiuyuan.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jiuyuan.entity.MailConstant;
import com.jiuyuan.entity.MailLog;
import com.jiuyuan.service.IMailLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @program: hrms
 * @description:
 * @author: Feng
 * @create: 2023-02-19 08:38
 **/


@Configuration
public class RabbitmqConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(RabbitmqConfig.class);

    @Autowired
    CachingConnectionFactory cachingConnectionFactory;
    @Autowired
    IMailLogService mailLogService;

    @Bean
    public RabbitTemplate rabbitTemplate(){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);

        /**
         * @Description: 确认消息是否达到broker
         * @data:消息唯一标识
         * @ack: 确认结果
         * @cause: 失败原因
         * @Date:2023/02/19 8:52
         */
        rabbitTemplate.setConfirmCallback((data,ack,cause)->{
            String msgId = data.getId();
            if(ack){
                LOGGER.info("{}===================发送成功",msgId);
                mailLogService.update(new UpdateWrapper<MailLog>().eq("msgId",msgId).set("status",MailConstant.SUCCESS));
            }else{
                LOGGER.info("{}===================发送失败",msgId);
            }
        });


        //消息失败回调，例如router达不到queue
        rabbitTemplate.setReturnsCallback((data)->{
            LOGGER.info("{}===================发送失败",data.getMessage().getBody());
        });

        return rabbitTemplate;
    }

    @Bean
    public Binding binding(){
        return BindingBuilder.bind(queue()).to(directExchange()).with(MailConstant.MAIL_ROUTING_KEY_NAME);
    }

    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange(MailConstant.MAIL_EXCHANGE_NAME);
    }

    @Bean
    public Queue queue(){
        return new Queue(MailConstant.MAIL_QUEUE_NAME);
    }
}
